<template>
  <div class="tbmandate">
    <div class="tbmandate_main">
      <el-card
        :body-style="{ padding: '0px', border: 'none' }"
        style="margin-bottom:10px"
        shadow="never"
      >
        <div class="tbm_top">
          <div class="displays " v-if="status == '2'">
            <p class="text">请绑定淘宝授权后继续操作</p>
            <!-- target="_blank" -->
            <a
              class="gomandate"
              href="https://oauth.taobao.com/authorize?spm=a219a.7386653.0.0.3617669a0M7Wly&response_type=code&client_id=30178134&redirect_uri=https://gy.letuilm.com/userinfo/pid&state=1212&view=web"
              rel="noopener noreferrer"
              >绑定授权</a
            >
          </div>
          <div class="displays" v-else>
            <p class="text">
              您绑定的授权账号<span style="color:red"> {{ nickname }}</span
              >已授权
            </p>
            <a
              class="gomandate"
              href="https://oauth.taobao.com/authorize?spm=a219a.7386653.0.0.3617669a0M7Wly&response_type=code&client_id=30178134&redirect_uri=https://gy.letuilm.com/userinfo/pid&state=1212&view=web"
              rel="noopener noreferrer"
              >更新授权</a
            >
            <p class="text">
              授权到期时间:
              <span v-if="expires_time == ''" style="color:red"> </span>
              <span v-else style="color:red">{{
                parseInt(expires_time) | formatTime("yyyy-MM-dd")
              }}</span>
              还有 <span style="color:red">{{ day }}</span> 天过期
            </p>
          </div>
        </div>
        <div class="tb_table">
          <el-table :data="tableData" style="width: 100%">
            <el-table-column prop="remark" label="分组名称">
              <template slot-scope="scope">
                <span>{{ scope.row.remark }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="pid" label="PID">
              <template slot-scope="scope">
                <span>{{ scope.row.pid }}</span>
              </template>
            </el-table-column>

            <el-table-column prop="type" label="类型标注(点击设置)">
              <template slot-scope="scope">
                <el-button type="text" @click="doEditPidType(scope.row)">{{
                  scope.row.type
                }}</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="active" label="操作">
              <template slot-scope="scope">
                <el-button type="text" @click="doedit(scope.row)"
                  >修改</el-button
                >
                <el-popconfirm
                  title="确定删除吗？"
                  @onConfirm="dodel(scope.row)"
                >
                  <el-button slot="reference" type="text">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div style="margin-top:20px;width:100%;text-align:left">
            <!-- 分页器 -->
            <!-- @size-change="handleSizeChange" -->
            <!-- background -->
            <el-pagination
              @current-change="handleCurrentChange2"
              :current-page="currentPage"
              :page-size="pagesize"
              :pager-count="11"
              layout="total, prev, pager, next, jumper"
              :total="count"
            >
              <!-- :page-sizes="[100, 200, 300, 400]" -->
            </el-pagination>
          </div>
          <!-- 新增 -->
          <div class="displays" style="margin:10px 0 25px 0;">
            <span style="margin:0 10px 0 10px;">备注名称:</span
            ><el-input
              v-model="remark"
              placeholder="请输入备注"
              clearable
              style="width:250px"
            ></el-input>
            <span style="margin:0 10px 0 10px;">PID:</span
            ><el-input
              v-model="pid"
              placeholder="请输入pid"
              style="width:250px"
              clearable
            ></el-input>
            <span style="margin:0 10px 0 10px;">类型选择:</span>
            <el-radio-group v-model="type" @change="typechange">
              <el-radio label="pid">pid</el-radio>
              <el-radio label="转链pid">转链pid</el-radio>
            </el-radio-group>
            <el-button style="margin-left:10px" type="primary" @click="doAddPid"
              >添加pid</el-button
            >
          </div>
        </div>
      </el-card>
      <el-dialog
        title="修改pid"
        :visible.sync="editopen"
        width="500px"
        :before-close="handleClose"
      >
        <el-form :model="form">
          <el-form-item label="pid" :label-width="formLabelWidth">
            <el-input v-model="form.pid" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="备注" :label-width="formLabelWidth">
            <el-input v-model="form.remark" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">取 消</el-button>
          <el-button type="primary" @click="doEditPid">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  getPidList,
  doAddPid,
  doEditPid,
  doDelPid,
  doEditPidType,
  bangTB,
  getBangStatus
} from "@/api/pid/pid";
export default {
  name: "tbmandate",
  filters: {
    formatTime: function(datetime, fmt) {
      var date = new Date(datetime);
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      var o = {
        "M+": date.getMonth() + 1,
        "d+": date.getDate(),
        "h+": date.getHours(),
        "m+": date.getMinutes(),
        "s+": date.getSeconds()
      };
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          var str = o[k] + "";
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length === 1 ? str : ("00" + str).substr(str.length)
          );
        }
      }
      return fmt;
    }
  },
  data() {
    return {
      formLabelWidth: "80px",
      editopen: false,
      status: "2",
      nickname: "",
      expires_time: "",
      day: "",
      form: {
        id: "", // 自增id
        pid: "", // pid
        remark: "" // 备注
      },
      tableData: [
        // {
        //   id: 1, // 自增id
        //   pid: 6, // pid
        //   remark: "测试", // 备注
        //   type: "pid" // 类型
        // }
      ],
      pagesize: 15,
      currentPage: 1,
      count: 0,
      remark: "", //备注输入框
      type: "pid", //类型单选框
      pid: "" //PID输入框
    };
  },

  computed: {},
  created() {
    console.log(this.$route);
    this.getPidList(1, 15);

    if (this.$route.query.code) {
      //绑定淘宝
      bangTB({
        code: this.$route.query.code
      })
        .then(res => {
          if (res.code == 200) {
            console.log("绑定返回", res);
            this.$message.success("绑定成功!");
            this.getBangStatus();
          } else {
            this.$message.info(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    } else {
      this.getBangStatus();
    }
  },
  mounted() {},
  methods: {
    //获取绑定状态
    getBangStatus() {
      getBangStatus()
        .then(res => {
          if (res.code == 200) {
            console.log("绑定状态返回", res);
            this.status = res.data.status;
            this.nickname = res.data.nickname;
            // this.nickname =
            // "%E9%98%BF%E4%B8%91%E4%B8%8D%E4%B8%91%E5%95%8A%E5%9";
            // "%E9%98%BF%E4%B8%91%E4%B8%8D%E4%B8%91%E5%95%8A%E5%95%8A%E5%95%8A";
            this.nickname = this.revertUTF8(this.nickname);

            this.expires_time = res.data.expires_time;
            // this.expires_time = "1594155999999";
            if (res.data.status == 1) {
              var obj = new Date();
              var year = obj.getFullYear();
              var month = obj.getMonth() + 1;
              var day = obj.getDate();
              var str =
                year.toString() + "-" + month.toString() + "-" + day.toString();
              // console.log(str);
              var newstr = new Date(parseInt(this.expires_time))
                .toLocaleDateString()
                .replace(/\//g, "-"); //年月日
              // console.log(newstr);
              var day1 = new Date(str);
              var day2 = new Date(newstr);
              this.day = (day2 - day1) / (1000 * 60 * 60 * 24);
            }
          } else {
            this.$message.info(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    //修改pid类型
    doEditPidType(row) {
      doEditPidType({
        id: row.id,
        type: row.type == "pid" ? "转链pid" : "pid"
      })
        .then(res => {
          if (res.code == 200) {
            console.log("返回", res);
            this.$message.success("类型修改成功!");

            this.getPidList(1, 15);
          } else {
            this.$message.info(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    //   修改pid
    doEditPid() {
      console.log(this.form);
      doEditPid({
        id: this.form.id,
        pid: this.form.pid,
        remark: this.form.remark
      })
        .then(res => {
          console.log(res);
          if (res.code == 200) {
            this.editopen = false;
            this.$message.success("修改成功!");
            this.getPidList(1, 15);
          } else {
            this.$message.info(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    // 关闭弹窗
    handleClose() {
      this.editopen = false;
      this.form = this.$options.data().form;
    },
    //新增
    doAddPid() {
      if (this.pid !== "" && this.remark !== "") {
        doAddPid({
          pid: this.pid,
          remark: this.remark,
          type: this.type
        })
          .then(res => {
            if (res.code == 200) {
              console.log("返回", res);
              this.$message.success("新增成功!");
              this.getPidList(1, 15);

              this.type = "pid";
              this.remark = "";
              this.pid = "";
            } else {
              this.$message.info(res.msg);
            }
          })
          .catch(err => {
            console.log(err);
          });
      } else {
        this.$message.info("请填写pid或者备注!");
      }
    },
    // 打开弹窗
    doedit(row) {
      this.editopen = true;
      let str = JSON.stringify(row);
      this.form = JSON.parse(str);
      console.log(this.form);
    },

    typechange(val) {
      console.log(val);
    },
    handleCurrentChange2(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.getPidList(this.currentPage, 15);
    },
    // 删除
    dodel(row) {
      console.log(row);
      doDelPid({
        id: row.id
      })
        .then(res => {
          console.log(res);
          if (res.code == 200) {
            this.$message.success("删除成功!");
            this.getPidList(1, 15);
          }
        })
        .catch(err => {
          console.log(err);
        });
    },

    revertUTF8(szInput) {
      var x,
        wch,
        wch1,
        wch2,
        szRet = "";
      for (x = 0; x < szInput.length; x++) {
        if (szInput.charAt(x) == "%") {
          wch = parseInt(szInput.charAt(++x) + szInput.charAt(++x), 16);
          if (!wch) {
            break;
          }
          if (!(wch & 0x80)) {
            // wch = wch;
          } else if (!(wch & 0x20)) {
            x++;
            wch1 = parseInt(szInput.charAt(++x) + szInput.charAt(++x), 16);
            wch = (wch & 0x1f) << 6;
            wch1 = wch1 & 0x3f;
            wch = wch + wch1;
          } else {
            x++;
            wch1 = parseInt(szInput.charAt(++x) + szInput.charAt(++x), 16);
            x++;
            wch2 = parseInt(szInput.charAt(++x) + szInput.charAt(++x), 16);
            wch = (wch & 0x0f) << 12;
            wch1 = (wch1 & 0x3f) << 6;
            wch2 = wch2 & 0x3f;
            wch = wch + wch1 + wch2;
          }
          szRet += String.fromCharCode(wch);
        } else {
          szRet += szInput.charAt(x);
        }
      }
      return szRet;
    },

    //获取用户设置pid列表
    getPidList(page, pagesize) {
      getPidList({
        page: page,
        pagesize: pagesize
      })
        .then(res => {
          if (res.code == 200) {
            console.log("pid返回", res);
            this.count = res.data.count;
            this.tableData = res.data.data;
            console.log(this.nickname);
          } else {
            this.$message.info(res.msg);
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  }
};
</script>

<style lang="less" scoped>
.tbmandate {
  .displays {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .tbmandate_main {
    .tbm_top {
      width: 100%;
      height: 50px;
      line-height: 50px;
      background-color: #97d3c5;
      //   background: linear-gradient(to right, blue, pink);
      .text {
        color: #fff;
        padding: 0 20px 0 20px;
      }
      .gomandate {
        display: inline-block;
        width: 90px;
        height: 25px;
        line-height: 25px;
        font-size: 14px;
        background-color: blue;
        border-radius: 12px;
        color: #fff;
      }
    }
  }
}
</style>
